package com.patentbackend.patentmanage.controller;

import com.patentbackend.patentmanage.dto.SliderDTO;
import com.patentbackend.patentmanage.entity.Slider;
import com.patentbackend.patentmanage.service.SliderService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/sliders")
public class SliderController {

    private final SliderService sliderService;

    public SliderController(SliderService sliderService) {
        this.sliderService = sliderService;
    }

    @GetMapping
    public ResponseEntity<List<Slider>> getAllSliders() {
        return ResponseEntity.ok(sliderService.findAll());
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Slider> createSlider(@Valid @RequestBody SliderDTO sliderDTO) {
        Slider slider = sliderService.create(sliderDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(slider);
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Slider> updateSlider(
            @PathVariable Long id,
            @Valid @RequestBody SliderDTO sliderDTO
    ) {
        if (!sliderService.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        Slider updatedSlider = sliderService.update(id, sliderDTO);
        return ResponseEntity.ok(updatedSlider);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Void> deleteSlider(@PathVariable Long id) {
        if (!sliderService.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        sliderService.delete(id);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/{id}/upload-image")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> uploadImage(
            @PathVariable Long id,
            @RequestParam("image") MultipartFile image
    ) throws IOException {
        if (!sliderService.existsById(id)) {
            return ResponseEntity.notFound().build();
        }
        String imageUrl = sliderService.uploadImage(id, image);
        return ResponseEntity.ok(imageUrl);
    }
}